package cn.rdq.iknesssystem.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.rdq.api.dto.EpisodeDto;
import cn.rdq.api.po.Episode;
import cn.rdq.api.vo.EpisodeVo;
import cn.rdq.dao.EpisodeMapper;
import cn.rdq.iknesssystem.service.EpisodeService;
import cn.rdq.iknesssystem.service.EpisodeSrcService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class EpisodeServiceImpl extends ServiceImpl<EpisodeMapper, Episode> implements EpisodeService {

    @Autowired
    private EpisodeMapper episodeMapper;

    @Autowired
    private EpisodeSrcService episodeSrcService;

    @Override
    public List<EpisodeDto> listEpisode(EpisodeVo episodeVo) {
        PageHelper.startPage(episodeVo.getPageNum(), episodeVo.getPageSize());
        return episodeMapper.listEpisode(episodeVo);
    }

    @Override
    public void saveEpisode(Episode episode) {
        QueryWrapper<Episode> wrapper = new QueryWrapper<>();
        wrapper.eq("name", episode.getName())
                .eq("drama_id", episode.getDramaId());
        Episode one = getOne(wrapper);
        if (ObjectUtil.isEmpty(one)) {
            episode.setCreateTime(new Date());
            episode.setUpdateTime(new Date());
            save(episode);
        }
    }

    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    @Override
    public void deleteEpisode(Long id) {
        boolean removed = removeById(id);
        if (removed) {
            episodeSrcService.deleteByEpisodeId(id);
        }
    }

    @Override
    public void deleteByDramaId(Long dramaId) {
        QueryWrapper<Episode> wrapper = new QueryWrapper<>();
        wrapper.eq("drama_id", dramaId);
        remove(wrapper);
    }
}
